/**
 * Copyright 2011 Renato de Jesus Manzoni
 * 
 * SED - Software Engineering and Dependability Research Group
 * 
 *     http://www.sed.ic.unicamp.br/
 * 
 * Distributed Systems Laboratory (LSD) in the Institute of Computing (IC) at University of Campinas (UNICAMP)
 * 
 *     http://www.lsd.ic.unicamp.br/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package br.unicamp.ic.lsd.wscaa.config;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

import br.unicamp.ic.lsd.wscaa.api.ExceptionHandler;

/**
 * @author Renato de Jesus Manzoni <rjmanzoni@gmail.com>
 * 
 */
public class ClientClassFactory {
    private URLClassLoader classLoader;
    private Map<String, ExceptionHandler> handlers;
    private static final String BASE_DIR = "jar:file://";

    /**
     * The client need to input the dir from jars files
     */
    public ClientClassFactory(File handlerClientJarDirPath) {

	URL[] jarFiles = findJarsInDir(handlerClientJarDirPath);

	classLoader = new URLClassLoader(jarFiles);

	handlers = new HashMap<String, ExceptionHandler>();
    }

    public ClientClassFactory(File handlerClientJarDirPath, ClassLoader classLoaderHandler) {

	URL[] jarFiles = findJarsInDir(handlerClientJarDirPath);

	classLoader = new URLClassLoader(jarFiles, classLoaderHandler);

	handlers = new HashMap<String, ExceptionHandler>();
    }
    
    public ExceptionHandler createHandlerInstance(String handlerClient) {
	ExceptionHandler clientHandler = handlers.get(handlerClient);
	if (clientHandler == null) {

	    try {
		@SuppressWarnings("unchecked")
		Class<ExceptionHandler> clientClass = (Class<ExceptionHandler>) Class
			.forName(handlerClient, true, classLoader);
		// JarURLConnection s =
		// (JarURLConnection)classLoader.getURLs()[0].openConnection();
		// new
		// JarResource().getJarContents("/Users/renatomanzoni/Documents/workspace_novo/maven-project/client-handler/target/client-handler-1.0-SNAPSHOT.jar");

		// new JarResource().getJarContents(classLoader.getURLs()[0]);
		clientHandler = (ExceptionHandler) clientClass.newInstance();
		handlers.put(handlerClient, clientHandler);

	    } catch (ClassNotFoundException e) {
		e.printStackTrace();
	    } catch (InstantiationException e) {
		e.printStackTrace();
	    } catch (IllegalAccessException e) {
		e.printStackTrace();
	    }
	}
	return clientHandler;
    }

    private URL[] findJarsInDir(File jarDir) {
	if (jarDir.isDirectory()) {

	    File[] jarFiles = jarDir.listFiles(new JARFilter());
	    URL[] urlJars = new URL[jarFiles.length];
	    for (int i = 0; i < jarFiles.length; i++) {
		File jarFile = jarFiles[i];
		try {
		    urlJars[i] = new URL(BASE_DIR + jarDir.getAbsolutePath()
			    + "/" + jarFile.getName() + "!/");
		} catch (MalformedURLException e) {
		    e.printStackTrace();
		}
	    }
	    return urlJars;
	}
	return null;

    }

    class JARFilter implements FilenameFilter {

	@Override
	public boolean accept(File dir, String name) {
	    return (name.endsWith(".jar"));
	}

    }
}
